package com.huang.pc;

/*
*     线程通信  生产消费问题！
*
* */
public class A {
    public static void main(String[] args) {
        Data data= new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"B").start();
    }

}
//判断等待  业务  通知
class Data{
    private int num=0;
    public synchronized void increment() throws InterruptedException {
        while (num!=0);{ //防止虚假唤醒  用while 不用if
            this.wait();
        }
         num++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        this.notify();
    }
    public synchronized void decrement() throws InterruptedException {
        while(num==0){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        this.notify();
    }
}
